//
//  ApplePayViewController.m
//  Study
//
//  Created by startiasoft on 2020/2/26.
//  Copyright © 2020 Startiasoft. All rights reserved.
//

#import "ApplePayViewController.h"

// 用户绑定的银行卡信息
#import <PassKit/PassKit.h>
// Apple pay的展示控件
#import <PassKit/PKPaymentAuthorizationViewController.h>
// 用户联系信息相关
#import <AddressBook/AddressBook.h>

@interface ApplePayViewController ()<PKPaymentAuthorizationViewControllerDelegate>

@end

@implementation ApplePayViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"Apple Pay";
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [btn setFrame:CGRectMake(0, 0, 200, 30)];
    btn.center = self.view.center;
    [btn setTitle:@"Apple Pay" forState:(UIControlStateNormal)];
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:btn];
    /**
        1.支持版本：iOS 8+（国内从9.2+开始支持）、iPhone 6+
        1.参考文献：
        Apple Card的使用：https://support.apple.com/zh-cn/HT204506
        集成使用：https://blog.csdn.net/weixin_33918114/article/details/92919676
        集成使用：https://www.cnblogs.com/fengfeng159/p/11122765.html
     */
}

// Button Click
- (void)btnClick:(UIButton *)sender{
    
    // 判断当前设备是否支持
    if(![PKPaymentAuthorizationViewController canMakePayments]) {
        NSLog(@"不能支付");
        return;
    }else{
        NSLog(@"可以支付");
    }
    
    // 判断"Wallet有没有添加该支付网络的储蓄卡/信用卡"

    if (![PKPaymentAuthorizationViewController canMakePaymentsUsingNetworks:@[PKPaymentNetworkAmex, PKPaymentNetworkMasterCard, PKPaymentNetworkVisa, PKPaymentNetworkChinaUnionPay]]) {
        NSLog(@"Wallet没有添加该支付网络的储蓄卡/信用卡");
        return;
    }else{
        NSLog(@"可以使用银行卡");
    }
    
    // 创建支付请求
    // 1. 创建一个支付请求
    PKPaymentRequest *request = [[PKPaymentRequest alloc] init];
     
    // 2. 参数配置
    // 2.1 商店标识
    request.merchantIdentifier = @"merchant.520it.com";
     
    // 2.2 货币代码
    request.currencyCode = @"CNY";
     
    // 2.3 国家编码
    request.countryCode = @"CN";
     
    // 2.4 支持的支付网络（PKPaymentNetworkChinaUnionPay iOS9.2开始支持）
    request.supportedNetworks = @[PKPaymentNetworkAmex, PKPaymentNetworkMasterCard, PKPaymentNetworkVisa, PKPaymentNetworkChinaUnionPay];
     
    // 2.5 支付请求包含一个支付摘要项目的列表
    NSDecimalNumber *price1 = [NSDecimalNumber decimalNumberWithString:@"2"];
    PKPaymentSummaryItem *item1 = [PKPaymentSummaryItem summaryItemWithLabel:@"手榴弹" amount:price1];
     
    NSDecimalNumber *price2 = [NSDecimalNumber decimalNumberWithString:@"6"];
    PKPaymentSummaryItem *item2 = [PKPaymentSummaryItem summaryItemWithLabel:@"炸弹" amount:price2 type:PKPaymentSummaryItemTypePending];
     
    NSDecimalNumber *totalAmount = [NSDecimalNumber zero];
    totalAmount = [totalAmount decimalNumberByAdding:price1];
    totalAmount = [totalAmount decimalNumberByAdding:price2];
    PKPaymentSummaryItem *total = [PKPaymentSummaryItem summaryItemWithLabel:@"小码哥财务中心" amount:totalAmount type:PKPaymentSummaryItemTypePending];
    // 注意: 数组最后一个是总价格
    request.paymentSummaryItems = @[item1, item2, total];
     
    // 2.6 运输方式
    NSDecimalNumber *shippingPrice = [NSDecimalNumber decimalNumberWithString:@"18.0"];
    PKShippingMethod *method = [PKShippingMethod summaryItemWithLabel:@"顺丰快递" amount:shippingPrice];
    method.detail = @"24小时送到！";
    method.identifier = @"shunfeng";
    request.shippingMethods = @[method];
    request.shippingType = PKShippingTypeServicePickup;
     
    // 2.7 通过指定merchantCapabilities属性来指定你支持的支付处理标准，3DS支付方式是必须支持的，EMV方式是可选的，
    request.merchantCapabilities = PKMerchantCapability3DS | PKMerchantCapabilityEMV | PKMerchantCapabilityCredit | PKMerchantCapabilityDebit;
     
    // 2.8 需要的配送信息和账单信息
    request.requiredBillingAddressFields = PKAddressFieldAll;
    request.requiredShippingAddressFields = PKAddressFieldAll;
     
    // 2.9 存储额外信息
    // 使用applicationData属性来存储一些在你的应用中关于这次支付请求的唯一标识信息，比如一个购物车的标识符。在用户授权支付之后，这个属性的哈希值会出现在这次支付的token中。
    request.applicationData = [@"购物车ID: 123456" dataUsingEncoding:NSUTF8StringEncoding];
    
    // 3. 开始支付
    PKPaymentAuthorizationViewController *paymentPane = [[PKPaymentAuthorizationViewController alloc] initWithPaymentRequest:request];
    if (paymentPane == nil) {
        NSLog(@"授权控制器创建失败");
        return;
    }
    paymentPane.delegate = self;
    [self presentViewController:paymentPane animated:YES completion:nil];
}


#pragma mark - Delegate
/**
*  当授权成功之后会调用这个代理方法
*/
- (void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller
                   didAuthorizePayment:(PKPayment *)payment
                            completion:(void (^)(PKPaymentAuthorizationStatus status))completion {
 
    // PKPayment *temp = payment;
    NSLog(@"验证授权---%@", payment.token);
    NSLog(@"验证通过后, 需要开发者继续完成交易");
    // 它需要你连接服务器并上传支付令牌和 其他信息，以完成整个支付流程。
    BOOL isSuccess = YES;
    if (isSuccess) {
        completion(PKPaymentAuthorizationStatusSuccess);
    }
    else {
        completion(PKPaymentAuthorizationStatusFailure);
    }
}


/**
*  当授权成功之后或者取消授权之后会调用这个代理方法
*/
- (void)paymentAuthorizationViewControllerDidFinish:(PKPaymentAuthorizationViewController *)controller {
    NSLog(@"取消或者交易完成");
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
